import { useAppProviderContext } from '@/components/Application';
import { isDevMode } from '@/utils/env';
import { downloadByData } from '@/utils/file/download';
import { multiply } from 'lodash-es';
import * as PDF from 'pdfjs-dist';
import 'pdfjs-dist/build/pdf.worker.entry';
import { onMounted, reactive, ref, unref } from 'vue';

export function useContractCanvas() {

  onMounted(() => {
    PDF.GlobalWorkerOptions.workerSrc = window['pdfjsWorker'];
  })

  let pdfDoc = {} as PDF.PDFDocumentProxy;


  const { isMobile } = useAppProviderContext()


  const contractCanvas = ref([] as CanvasImageSource[]);

  const state = reactive({
    /** 当前正在操作的pdf文件地址 */
    pdfFile: import.meta.env.VITE_PUBLIC_PATH + '/src/assets/pdf/file/Signed_Organize.pdf',
    /** 当前页数 */
    currentPage: 0,
    /** 总页数 */
    pdfPages: 0,
    /** 放大倍数 */
    pdfScale: 2,
    /** 是否正在加载 */
    loading: false
  });



  function register(ref, index) {
    contractCanvas.value[index] = ref
  }

  function loadFile(url) {
    if (!url) return
    if (isDevMode() && url.includes('https')) url = '/contract' + url.split('.com/contract')[1]

    state.pdfFile = url;
    let loadingTask = PDF.getDocument(url);
    return loadingTask.promise.then((pdf: any) => {
      pdfDoc = pdf;

      state.pdfPages = pdf.numPages;
      state.currentPage = 1;

    }).catch(err => {
      console.log(err);
    })
  }

  async function renderPage(canvas, num: number) {
    state.loading = true;
    try {
      var outputScale = window.devicePixelRatio || 1;

      const page = await pdfDoc.getPage(num);
      var context = canvas.getContext('2d');
      if (!context) return;

      var viewport = page.getViewport({
        scale: state.pdfScale,
      })


      var transform = outputScale !== 1
        ? [outputScale, 0, 0, outputScale, 0, 0]
        : null;

      if (isMobile) {
        canvas.width = Math.floor(viewport.width * outputScale);
        canvas.height = Math.floor(viewport.height * outputScale);
        canvas.style.width = '100%';
        canvas.style.height = "auto";

      } else {
        canvas.width = Math.floor(viewport.width * outputScale);
        canvas.height = Math.floor(viewport.height * outputScale);
        canvas.style.width = Math.floor(viewport.width) + "px";
        canvas.style.height = Math.floor(viewport.height) + "px";
      }


      await page.render({
        canvasContext: context,
        viewport: viewport,
        transform: transform || undefined
      }).promise;
      state.currentPage = num;
    } catch (error) {
      console.error(error);
    } finally {
      setTimeout(() => {
        state.loading = false;
      }, 100);
    }
  }


  //渲染生成图片
  function renderImg() {
    const canvasList = unref(contractCanvas)
    const newCanvas = document.createElement('canvas')
    const size = [794, 1123].map(multiply.bind(null, 2))
    newCanvas.width = size[0]
    newCanvas.height = size[1] * canvasList.length
    const context = newCanvas.getContext('2d')
    canvasList.forEach((item, i) => {
      context!.drawImage(item, 0, i * size[1], size[0], size[1])
    })

    return {
      base64: () => newCanvas.toDataURL('image/jpeg'),
      bold: () => new Promise<Blob>(res => newCanvas.toBlob(blob => blob && res(blob), 'image/jpeg'))
    }
  }

  async function downloadFile() {
    state.loading = true;
    try {
      const res = await pdfDoc.getData();

      downloadByData(res, 'test.pdf');
    } catch (error) {
      console.error(error);
    } finally {
      state.loading = false;
    }
  }

  return [
    register,
    {
      state,
      contractCanvas,
      loadFile,
      renderPage,
      renderImg,
      downloadFile
    }
  ] as const
}

export type ContractCanvasClass = (ReturnType<typeof useContractCanvas>)[1]
